package com.cy.pj.sys.web.controller;

import com.cy.pj.common.exception.ServiceException;
import com.cy.pj.common.pojo.JsonResult;
import com.cy.pj.common.util.PageUtil;
import com.cy.pj.sys.pojo.SysUser;
import com.cy.pj.sys.service.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user/")
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;

    @GetMapping("login/{username}/{password}")
    public JsonResult doLogin(@PathVariable String username,
                              @PathVariable String password){
        //控制层方法拿到用户名和密码以后要将这个信息提交给谁?(shiro)
        //通过谁提交？Subject
        //如何获取Subject?参考官方或源代码
        Subject subject= SecurityUtils.getSubject();
        //如何提交用户和密码？(调用subject对象的login方法)
        //为什么要构建UsernamePasswordToken对象？因为login方法需要
        AuthenticationToken token=
                new UsernamePasswordToken(username, password);

        ((UsernamePasswordToken) token).setRememberMe(true);//设置记住我

        subject.login(token);//提交给shiro的securityManager
        return new JsonResult("login ok");
    }

    @PatchMapping("{id}/{valid}") //@PatchMapping 应用与少量数据更新
    public JsonResult doValidById(@PathVariable Integer id,@PathVariable Integer valid){
        sysUserService.validById(id, valid);
        return new JsonResult("update ok");
    }

    @PutMapping
    public JsonResult doUpdateUser(@RequestBody SysUser sysUser) throws ServiceException {
        sysUserService.updateUser(sysUser);
        return new JsonResult("update ok");
    }

    @PostMapping
    public JsonResult doSaveUser(@RequestBody SysUser sysUser){
        sysUserService.saveUser(sysUser);
        return new JsonResult("save ok");
    }

    @GetMapping("{id}")
    public JsonResult doFindById(@PathVariable Integer id) throws ServiceException {
        return new JsonResult(sysUserService.findById(id));
    }

    @RequiresPermissions("sys:user:view")
    @GetMapping
    public JsonResult doFindUsers(SysUser sysUser){
        return new JsonResult(PageUtil.startPage().doSelectPageInfo(()->{
            sysUserService.findUsers(sysUser);
        }));//结果交给谁？DispatcherServlet
    }
}











































